package common

import (
	"database/sql"
	"fmt"
	"strings"
	"time"

	_ "github.com/go-sql-driver/mysql"
	"github.com/jmoiron/sqlx"
)

var db *sqlx.DB

type Administrators struct {
	ID        int64        `db:"id"`
	UserName  string       `db:"user_name"` // 用户登录名
	NickName  string       `db:"nick_name"` // 用户昵称
	Password  string       `db:"password"`  // 用户密码
	Email     string       `db:"email"`     // email
	Mobile    string       `db:"mobile"`    // 手机号
	Salt      string       `db:"salt"`      // salt
	Status    int          `db:"status"`    // 用户状态(0:禁用1:启用)
	CreatedAt time.Time    `db:"created_at"`
	UpdatedAt time.Time    `db:"updated_at"`
	DeletedAt sql.NullTime `db:"deleted_at"`
}

func initDB() (err error) {
	dsn := "root:root@tcp(127.0.0.1:3306)/dataplatform?charset=utf8mb4&parseTime=True"
	// 也可以使用MustConnect连接不成功就panic
	db, err = sqlx.Connect("mysql", dsn)
	if err != nil {
		fmt.Printf("connect DB failed, err:%v\n", err)
		return
	}
	db.SetMaxOpenConns(20)
	db.SetMaxIdleConns(10)
	return
}

// 查询单条数据示例
func queryRowDemo() {
	sqlStr := "select id, name, age from administrator where id=?"
	var u Administrators
	err := db.Get(&u, sqlStr, 1)
	if err != nil {
		fmt.Printf("get failed, err:%v\n", err)
		return
	}
	fmt.Printf("id:%d name:%s age:%d\n", u.ID, u.UserName, u.Mobile)
}

func generateWhere(where map[string]interface{}) ([]string, []interface{}) {
	var whereSlice []string
	var bindSlice []interface{}

	for condition, v := range where {
		whereSlice = append(whereSlice, condition)
		bindSlice = append(bindSlice, v)
	}

	return whereSlice, bindSlice
}

func Test() {
	initDB()

	where := map[string]interface{}{
		"id = ?":         1,
		"nick_name != ?": "demo008",
	}

	s, bindSlice := generateWhere(where)

	sqlStr := fmt.Sprintf("select id, nick_name, email from administrators where %s", strings.Join(s, " and "))

	var u Administrators

	err := db.Get(&u, sqlStr, bindSlice...)
	if err != nil {
		fmt.Printf("get failed, err:%v\n", err)
		return
	}
	fmt.Printf("id:%d nick_name:%s email:%s\n", u.ID, u.NickName, u.Email)
}
